1770E - Koxia and Tree - CodeForces Solution


combinatorics dfs and similar dp dsu math probabilities trees *2400

Please click on ads to support us..

C++ Code:

#include <bits/stdc++.h>
#define maxn 302333
#define maxm 606666
using namespace std;
using i64 = long long;
const i64 mod = 998244353;
const i64 inv2 = 499122177;
i64 Pow(i64 x, i64 p) {
	i64 r = 1;
	for (; p; p >>= 1, x = x * x % mod) if (p & 1) r = r * x % mod;
	return r;
}
int head[maxn], nxt[maxm], to[maxm], ec = 1, fa[maxn];
int siz[maxn], is[maxn];
void add(int u, int v) {
	nxt[++ec] = head[u], head[u] = ec, to[ec] = v;
}
i64 n, k;
i64 ans = 0;
i64 poss[maxn];
void dfs(int x) {
	siz[x] = is[x];
	for (int e = head[x]; e; e = nxt[e]) {
		if (to[e] != fa[x]) {
			fa[to[e]] = x;
			dfs(to[e]);
			siz[x] += siz[to[e]];
		}
	}
}
void calc_ans(int x) {
	for (int e = head[x]; e; e = nxt[e]) {
		if (to[e] != fa[x]) {
			ans += (i64) siz[to[e]] * (k - siz[to[e]]);
			calc_ans(to[e]);
		}
	}
}
int main() {
	scanf("%lld%lld", &n, &k);
	for (int i = 1, x; i <= k; ++i) scanf("%d", &x), is[x] = 1, poss[x] = 1;
	for (int i = 1, u, v; i < n; ++i) {
		scanf("%d%d", &u, &v);
		add(u, v), add(v, u);
	}
	dfs(1);
	calc_ans(1);
	for (int i = 1, e = 2; i < n; ++i, e += 2) {
		int u = to[e ^ 1], v = to[e];
		if (fa[u] == v) swap(u, v); // u is now father for sure
		ans = (ans + (
				((k - siz[v] - 1) - siz[v] + mod) * poss[u] % mod * (mod + 1 - poss[v]) % mod
				+ ((siz[v] - 1) - (k - siz[v]) + mod) * (mod + 1 - poss[u]) % mod * poss[v] % mod
				) * inv2 % mod) % mod;
		poss[u] = poss[v] = (poss[u] + poss[v]) * inv2 % mod;
	}
//	printf("%lld\n", ans);
	printf("%lld\n", ans * 2 * Pow(k * (k - 1) % mod, mod - 2) % mod);
	return 0;
}


Comments

Submit
0 Comments
More Questions

903C - Boxes Packing
887A - Div 64
755B - PolandBall and Game
808B - Average Sleep Time
1515E - Phoenix and Computers
1552B - Running for Gold
994A - Fingerprints
1221C - Perfect Team
1709C - Recover an RBS
378A - Playing with Dice
248B - Chilly Willy
1709B - Also Try Minecraft
1418A - Buying Torches
131C - The World is a Theatre
1696A - NIT orz
1178D - Prime Graph
1711D - Rain
534A - Exam
1472A - Cards for Friends
315A - Sereja and Bottles
1697C - awoo's Favorite Problem
165A - Supercentral Point
1493A - Anti-knapsack
1493B - Planet Lapituletti
747B - Mammoth's Genome Decoding
1591C - Minimize Distance
1182B - Plus from Picture
1674B - Dictionary
1426C - Increase and Copy
520C - DNA Alignment